package com.home.webapp.client.service;

import com.home.common.constants.redis.RedisDateBase;
import com.home.common.redis.RedisUtil;
import com.home.common.utils.object.ObjectUtils;
import com.home.webapp.common.constants.dict.DictDataStatusConstant;
import com.home.webapp.client.mapper.DictDataOutMapper;
import com.home.webapp.common.entity.DictDataOut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 数据字典接口,thymeleaf直接调用
 * Created by 王大宸 on 2020-10-06 0:07
 * Created with IntelliJ IDEA.
 */
@Service("dict")
public class DictServer {
    private static final Logger logger = LoggerFactory.getLogger(DictServer.class);
    @Autowired
    private DictDataOutMapper dictDataMapper;

    /***
     * 功能说明：根据数据字典类型查询数据字典的值
     *
     * @author 王大宸
     * @date 2020/10/6 0:10
     * @param dictType 数据字典类型
     * @return java.util.List<com.home.security.auth.entity.SysDictData>
     */
    public List<DictDataOut> getType(String dictType) {
        try {
            Object obj = RedisUtil.get(RedisDateBase.DICT_DATA_REDIS_KEY + dictType + RedisDateBase.CHILDREN_SUFFIX, RedisDateBase.DEFAULT_DATE_BASE);
            if (null == obj) {
                return dictDataMapper.getType(dictType, DictDataStatusConstant.IS_OK);
            }
            return (List<DictDataOut>) obj;
        } catch (Exception e) {
            logger.error("获取数据字典失败: " + e.toString());
            return new ArrayList<>();
        }
    }

    /***
     * 功能说明：根据数据字典类型和数据字典值查询数据
     *
     * @author 王大宸
     * @date 2020/10/6 0:10
     * @param dictType    数据字典类型
     * @param dictValue   数据字典值
     * @return java.lang.String
     */
    public String getDictLabel(String dictType, String dictValue) {
        Object obj = RedisUtil.get(RedisDateBase.DICT_DATA_REDIS_KEY + dictType + "_" + dictValue, RedisDateBase.DEFAULT_DATE_BASE);
        if (null == obj) {
            return dictDataMapper.getDictLabel(dictType, dictValue);
        }
        DictDataOut dictData = ObjectUtils.objToClass(obj, DictDataOut.class);
        return dictData.getDictLabel();
    }

}
